package com.example.demo.leetcode;

import java.util.ArrayList;
import java.util.List;

/**
 * 链接：<a href="https://leetcode.cn/problems/remove-nth-node-from-end-of-list/?envType=study-plan-v2&envId=top-interview-150">https://leetcode.cn/problems/remove-nth-node-from-end-of-list/?envType=study-plan-v2&envId=top-interview-150</a>
 *
 * @author WangYX
 * @version 1.0.0
 * @date 2024/02/02 13:49
 */
public class _19_删除链表的倒数第N个节点 {

    public ListNode removeNthFromEnd(ListNode head, int n) {
        if (head.next == null) {
            return null;
        }
        List<ListNode> list = new ArrayList<>();
        while (head != null) {
            list.add(head);
            head = head.next;
        }
        int i = list.size() - n;
        if (i == 0) {
            return list.get(1);
        } else {
            ListNode pre = list.get(i - 1);
            if (i == list.size() - 1) {
                pre.next = null;
            } else {
                ListNode suffix = list.get(i + 1);
                pre.next = suffix;
            }
            return list.get(0);
        }
    }
}
